// pages/member-friendRule/member-friendRule.js
import api from '../../utils/api.js'
let app = getApp();
import QR from '../../utils/qrcode.js'
import { config } from '../../utils/config'
import {
    HTTP
} from '../../utils/http.js';
let http = new HTTP();
Page({

    /**
     * 页面的初始数据
     */
    data: {
        // 此页面 页面内容距最顶部的距离
        height: app.globalData.height * 2 + 20,
        share: false, // 页面进入方式：是否由分享进入
        percent: 0,
        showModel: false,
        nickName: '',
        downloadUrl: '',
        imgUrl: config.imgUrl,
        imagePath: "" //二维码图片地址
    },
    //去积分商城
    goShop() {
        wx.navigateTo({
            url: "/pages/shop/shop",
        })
    },
    //web-view下载
    goDownLoad(e) {
        wx.navigateTo({
            url: "/pages/downLoadApp/downLoadApp",
        })
    },

    // 判断用户是否登录


    onLoad: function (options) {
        console.log('=========onload=========')
        let size = this.setCanvasSize(); //动态设置画布大小
        this.getAppQrCode(size.w, size.h);
        let isAuth = wx.getStorageSync('is_auth');
        console.log('options', options)
        if (options.user_id && isAuth) {
            //比如 商家由微信好友分享 进入推荐码页面，点击下载app
            // 分享的页面应是 推荐人的 推荐码，而不是商家的
            this.setData({
                invite_code: options.invite_code,
                nickName: options.nickName,
                share: true
            })
        } else {
            let nickName = wx.getStorageSync('nickName');
            let user_id = wx.getStorageSync("user_id")
            this.sureInviteCode(user_id)
            this.setData({
                nickName
            })
        }
    },

    onShow: function () {

    },

    //判断用户是否已有邀请码
    sureInviteCode(id) {
        http.request({
            url: sureInviteCode,
            data: {
                id: id
            },
            success: (res) => {
                if (res.data == 1) {
                    //该用户已有推荐码
                    let msg = res.message
                    this.getInviteCode(id);
                } else {
                    //该用户还没有相关推荐码
                    this.getNewUserInviteCode(id)
                }
            }
        })
    },
    //新版本生成用户唯一邀请码
    getNewUserInviteCode(id) {
        http.request({
            url: api.getNewUserCode,
            data: {
                id: id
            },
            success: (res) => {
                console.log('创建成功', res)

                this.getInviteCode(id);
            }
        })
    },
    //已有，获取邀请码
    getInviteCode(id) {
        http.request({
            url: api.getInviteCode,
            data: {
                id: id
            },
            success: (res) => {
                console.log('我的推荐码', res)

                this.setData({
                    invite_code: res.invite_code
                })
            }
        })
    },
    copyText: function (e) {
        let invite_code = this.data.invite_code;
        console.log(e)
        wx.setClipboardData({
            data: invite_code,
            success: function (res) {
                wx.getClipboardData({
                    success: function (res) {
                        console.log(res)
                        wx.showToast({
                            title: '复制成功'
                        })
                    }
                })
            }
        })
    },

    //获取相册授权,保存二维码
    saveImg() {
        // wx.getSetting({
        //   success(res) {
        //     if (!res.authSetting['scope.writePhotosAlbum']) {
        //       wx.authorize({
        //         scope: 'scope.writePhotosAlbum',
        //         success() {
        //           console.log('授权成功')
        //         }
        //       })
        //     }
        //   }
        // })
        let that = this;
        wx.getImageInfo({ //将获取图片的信息
            src: '{{imgUrl}}/images/member/wg_apk.png', // 需要下载的图片
            success(res) {
                let filePath = res.path //得到本地的路径
                wx.saveImageToPhotosAlbum({
                    filePath: filePath,
                    success(res) {
                        console.log(res)
                        wx.showToast({
                            title: '保存成功',
                            icon: 'success'
                        })
                    }
                })
            }
        })
    },
    //获取安装包地址，生成canvas
    getAppQrCode(w, h) {
        http.request({
            url: api.getVersion,
            success: (res) => {
                console.log('1111111111', res);
                if (res.code == 200) {
                    let downloadUrl = res.data.download;
                    this.createQrCode(`${downloadUrl}`, 'mycanvas', w, h)
                    this.setData({
                        downloadUrl
                    })
                }
            }
        })

    },
    //适配不同屏幕大小的canvas
    setCanvasSize: function () {
        var size = {};
        try {
            var res = wx.getSystemInfoSync(); //不同屏幕下canvas的适配比例；设计稿是750宽
            var scale = 3.7;
            var width = res.windowWidth / scale;
            var height = width; //canvas画布为正方形
            size.w = width;
            size.h = height;
        } catch (e) {
            // Do something when catch error
            console.log("获取设备信息失败" + e);
        }
        return size;
    },
    //生成二维码
    createQrCode: function (content, canvasId, cavW, cavH) {


        //调用插件中的draw方法，绘制二维码图片
        QR.api.draw(content, canvasId, cavW, cavH);
        // this.canvasToTempImage(canvasId);
        setTimeout(() => { this.canvasToTempImage(canvasId); }, 10);
    },

    //获取临时缓存图片路径，存入data中
    canvasToTempImage: function (canvasId) {
        var that = this;
        wx.canvasToTempFilePath({
            canvasId, // 这里canvasId即之前创建的canvas-id
            success: function (res) {
                var tempFilePath = res.tempFilePath;
                console.log(tempFilePath);
                that.setData({ // 如果采用mpvue,即 this.imagePath = tempFilePath
                    imagePath: tempFilePath,
                });
            },
            fail: function (res) {
                console.log(res);
            }
        });
    },

    //点击图片进行预览，长按保存分享图片
    previewImg: function (e) {
        let img = this.data.imagePath;
        console.log(img);
        wx.previewImage({
            current: img, // 当前显示图片的http链接
            urls: [img] // 需要预览的图片http链接列表
        })
    },
    onShareAppMessage(res) {
        console.log('ppp', res)
        console.log(this.data)
        let user_id = wx.getStorageSync("user_id");
        let nickName = this.data.nickName;
        let invite_code = this.data.invite_code;
        // if (res.from === 'button') { //button  menu
        //   console.log(1111111111)
        //   // 来自页面内转发按钮
        //   var content = {
        //     title: 'APP下载',
        //     path: `/pages/index/index?redirect=/pages/member-friendRule/member-friendRule&invite_code=${invite_code}&user_id=${user_id}&nickName=${nickName}`,
        //     success: function(res) {
        //       console.log('成功', res)
        //     }
        //   }
        // }

        var content = {
            title: '味歌分享奖汽车',
            path: `/pages/member-friendRule/member-friendRule?invite_code=${invite_code}&user_id=${user_id}&nickName=${nickName}&typeShare=1`,
            success: function (res) {
                console.log('成功', res)
            }
        }
        return content
    },

    userShareEnter(options) {
        console.log('options', options)
        //由分享进入时，别人进入你的分享时
        if (options.typeShare == 1) {
            let nickName = wx.getStorageSync('nickName');
            //若用户已授权
            if (nickName) {
                //存在，即已经获得授权
                this.setData({
                    share: false
                })
            } else {
                //没获得授权时， 显示授权按钮
                this.setData({
                    authorizeBtn: true
                })
            }
        }

        wx.updateShareMenu({
            withShareTicket: true
        })
    },
    // 点击 tab 时触发
    onTabItemTap(item) {
        console.log(item.index)
        console.log(item.pagePath)
        console.log(item.text)
        if (!wx.getStorageSync('is_auth')) {
            wx.showToast({
                title: '请先登录',
                icon: 'none',
                duration: 1500
            })
            setTimeout(() => {
                wx.reLaunch({
                    url: '/pages/my/my'
                })
            }, 1000)
        }
    }
})